import React, { useRef, useEffect, useCallback } from 'react';
import events from '@/utils/eventBus';
import EVENTBUS_TYPES from '@/pages/Recruitment/Interview/utils/EVENTBUS_TYPES';
import WARNING_TYPES from '@/pages/Recruitment/Interview/utils/WARNING_TYPES';
/**
 * 警告声播放器
 */
const AlarmAudioPlayer = ({ recData, userCode, recHOSTuserCode, warningType }) => {
    const audioRef = useRef(null);

    const play = useCallback(async () => {
        console.log('==ALARM==> 播放警示音！');
        try {
            await audioRef.current.play();
        } catch (error) {
            console.log('音频播放失败，浏览器限制', error);
        }
    }, []);
    /**
     * 处理需要播放警示音的情况
     */
    const alarmHandler = () => {
        if (recData.recordUrlState === 1) return;
        console.log('=======alarmHandler========>', warningType);
        // error 麦克风故障； warning 无音浪
        if (WARNING_TYPES.RED_LIST.includes(warningType) || warningType === WARNING_TYPES.NOTICE) {
            play();
        }
        if (userCode !== recHOSTuserCode && warningType === WARNING_TYPES.PAUSED) {
            play(); // 非主录音者，在主录音停止之后
        }
    };

    useEffect(() => {
        alarmHandler();
    }, [warningType]);

    useEffect(() => {
        events.addListener(EVENTBUS_TYPES.PLAY_ALARM, play);
        return () => {
            events.removeListener(EVENTBUS_TYPES.PLAY_ALARM, play);
        };
    }, []);

    // eslint-disable-next-line
    return <audio style={{ display: 'none' }} ref={audioRef} src="/music/RECError.mp3" preload="auto"></audio>;
};

export default React.memo(AlarmAudioPlayer);
